package com.freesun.shop.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.service.SysUserService;
import com.freesun.shop.mapper.SysRoleMapper;
import com.freesun.shop.mapper.SysUserRoleMapper;
import com.freesun.shop.param.UserParam;
import com.freesun.shop.vo.Auth;
import com.freesun.shop.entity.SysRole;
import com.freesun.shop.entity.SysUser;
import com.freesun.shop.mapper.SysUserMapper;
import com.freesun.shop.entity.SysUserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private static Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);



    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public SysUser getById(Serializable id) {
        log.info("查询Id为:{}的用户",id);
        SysUser sysUser = super.getById(id);
        List<Object> roleIdList = sysUserRoleMapper.selectObjs(new LambdaQueryWrapper<SysUserRole>()
                .select(SysUserRole::getRoleId)
                .eq(SysUserRole::getUserId, id));
        sysUser.setRoleIdList(roleIdList);
        return sysUser;
    }

    /**
     * 修改用户
     * @param sysUser
     */
    @Override
    //@CacheEvict(cacheNames = )
    public void updateUser(SysUser sysUser) {
        Assert.notNull(sysUser,"修改时对象不能为null");
        Assert.notNull(sysUser.getUserId(),"修改时对象ID不能为null");
        log.info("修改用户,本次修改用户ID为:{}",sysUser.getUserId());
        SysUser userDb = getById(sysUser.getUserId());
        if(null==userDb){
            throw new RuntimeException("要修改的用户不存在");
        }
        //修改密码
        this.baseMapper.updateById(sysUser);
        //修改其他表
        List<Object> dbRoleIdList = userDb.getRoleIdList();
        List<Object> roleIdList = sysUser.getRoleIdList();

        boolean flag=true;
        if(dbRoleIdList.size()==roleIdList.size()){
            for (Object object : roleIdList) {
                if(!dbRoleIdList.contains(object)){
                    flag=false;
                }
            }
        }else {
            flag=false;
        }
        if(!flag){
            //删除用户的菜单缓存还有权限缓存
            redisTemplate.delete("com.freesun.shop.vo.MenuAuths::"+sysUser.getUserId());
            //删除用户缓存的权限值
            redisTemplate.delete(Auth.USER_AUTH_PREFIX+sysUser.getUserId());
            //先删除之前的角色,再增加现在的值
            if(!dbRoleIdList.isEmpty()){
                sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getRoleId,dbRoleIdList));
            }
            for (Object object : roleIdList) {
                SysUserRole sysUserRole= new SysUserRole();
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setRoleId(Long.valueOf(object.toString()));
                sysUserRoleMapper.insert(sysUserRole);
            }

        }
    }

    /**
     * 新增用户
     */
    @Override
    @Transactional
    public void addUser(UserParam userParam) {
        Assert.notNull(userParam,"新增用户不能为null");
        Assert.notNull(userParam.getUsername(),"新增用户名不能为null");
        SysUser sysUser=new SysUser();
        BeanUtils.copyProperties(userParam,sysUser);
        sysUser.setCreateTime(LocalDateTime.now(ZoneId.of("GMT+8")));
        //HashUtils.getHashWithSalt(sysUser.getPassword(),"whsxt")
        //暂时定好密码
        sysUser.setPassword("b53b8594f4e0ec33b5f3ed8c29c2a81b");
        this.baseMapper.insert(sysUser); //新增用户
        List<Long> roleIdList = userParam.getRoleIdList();
        for (Long roleId : roleIdList) {
            Integer num = sysRoleMapper.selectCount(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleId, roleId));
            if(null==num||num==0){
                throw new RuntimeException("用户输入的角色不存在");
            }else {
                SysUserRole sysUserRole=new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRoleMapper.insert(sysUserRole);
            }
        }
    }
    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @Override
    @Transactional  //事务问题同意提交
    public Boolean deleteUserByIds(List<Long> ids) {
        Assert.notEmpty(ids,"删除的集合不能为null");
       ids.forEach((userId) -> deleteUserById(userId));

        /*int isOk = this.baseMapper.deleteBatchIds(ids);
        log.info("删除的用户id为:{}",ids);
        //删除用户角色中间表
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId,ids));

        //删除用户的权限缓存数据
        ids.forEach((userId)->{
            redisTemplate.delete(Auth.USER_AUTH_PREFIX+userId);
            redisTemplate.delete("com.freesun.shop.vo.MenuAuths::"+userId);
        });*/
        return Boolean.TRUE;
    }

    @Override
   // @CacheEvict(cacheNames = "com.freesun.shop.vo.MenuAuths",key = "#userId")
    public Boolean deleteUserById(Long userId) {
        System.out.println("删除userId");
        this.baseMapper.deleteById(userId);
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        redisTemplate.delete(Auth.USER_AUTH_PREFIX+userId);
        redisTemplate.delete("com.freesun.shop.vo.MenuAuths::"+userId);
        return Boolean.TRUE;
    }

    /**
     * 按条件查询用户信息

     * @param sysUser
     * @param page
     * @return
     */
    @Override
    public IPage<SysUser> findSysUserPage(SysUser sysUser, Page<SysUser> page) {
        IPage<SysUser> sysUserIPage = this.baseMapper.selectPage(page, new LambdaQueryWrapper<SysUser>()
                .like(StringUtils.hasText(sysUser.getUsername()), SysUser::getUsername, sysUser.getUsername()));
        return sysUserIPage;
    }



    /**
     * 用户登陆验证
     * @param username
     * @return
     */
    @Override
    public SysUser findUserByName(String username) {
        if(!StringUtils.hasText(username)){
            throw new RuntimeException("用户名不能为空");
        }
        log.info("查询用户:{}",username);
        List<SysUser> users = this.baseMapper.selectList(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
                        .eq(SysUser::getStatus,1));
        if(users.isEmpty()){
            return null;
        }
        if(users.size()>1){
            log.error("用户名:{},存在多个用户",username);
            throw new RuntimeException("用户名不唯一,可能是数据库迁移错误。");
        }
        return users.get(0);
    }
}
